package main.java.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

/**
 * 维护连接池对象
 * 对外提供在ThreadLocal连接的方法
 * 对外提供释放连接的方法
 */
public class JDBCUtil {
    private static DataSource dataSource;
    private static ThreadLocal <Connection>threadLocal = new ThreadLocal<>();

    static{
        try {
            //1.创建Properties集合,用于存储外部配置文件的key和value值。
            Properties properties = new Properties();

            //2.读取外部配置文件,获取输入流,加载到Properties集合里。
            InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("main/resources/db.properties");
            if (inputStream == null) {
                throw new FileNotFoundException("无法找到db.properties 文件，请检查路径是否正确！");
            }
            properties.load(inputStream);

            //3.基于Properties集合构建DruidDataSource连接池
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //对外提供释放连接的方法
    public static Connection getConnection(){
        try {
            //在ThreadLocal中获取连接
            Connection connection = threadLocal.get();
            if(connection == null){
                //从连接池中获取连接
                connection = dataSource.getConnection();
                //将连接存入ThreadLocal中
                threadLocal.set(connection);
            }
            return connection;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //对外提供回收连接的方法
    public static void releaseConnection(Connection connection){
        try {
            if(connection != null){
                connection.close();
                threadLocal.remove();
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
